<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <el-alert
        title="注意：只能选择三级商品分类信息"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <!--选择商品分类-->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!--级联-->
          <el-cascader
            style="width: 40%"
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            clearable
            @change="handleChange"
            >
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--添加动态参数的面板-->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <!--索引列-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item,i) in (scope.row.attr_vals)" closable
                 @close="handleClose(i,scope.row)">
                    {{item}}
                </el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--添加按钮-->
                <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit"
                           size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--添加静态属性的面板-->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>

          <el-table :data="onlyTableData" border stripe>
            <!--索引列-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item,i) in (scope.row.attr_vals)" closable
                        @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--添加按钮-->
                <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--添加dialog-->
    <el-dialog :title="'增加'+titleText" :visible.sync="addDialogVisible" width="50%"
    @close="addDialogClosed">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules"  ref="addFormRef"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改对话框-->
    <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%"
               @close="editDialogClosed">
    <!--内容主体区域-->
      <el-form :model="editForm" :rules="addFormRules"  ref="editFormRef"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  let catejson=require('./json/cate.json')
  let manyjson=require('./json/ManyParams.json')
  let onlyjson=require('./json/OnlyParams.json')

  export default {
    name: "CateParams",
    data(){
      return{
        //商品分类列表
        cateList:[],
        //级联选择框的配置对象
        cateProps:{
          expandTrigger:"hover",
          value:'id',
          label:'cat_name',
          children:'children'
        },
        //级联选择框双向绑定到的数组
        selectedKeys:[],
      //  被激活的tab的名称
        activeName:'many',
        manyTableData:[],
        onlyTableData:[],
        addDialogVisible:false,
        addForm:{
          attr_name:''
        },
        addFormRules:{
          attr_name:[
            {required: true,message:'请输入参数名称',trigger:'blur'},
          ]
        },
        editDialogVisible:false,
        editForm:{
          attr_name:''
        }
      }
    },
    created(){
      this.getCateList();
    },
    computed:{
    //  如果按钮需要禁用，则返回true，否则false
      isBtnDisabled(){
        if(this.selectedKeys.length!==3){
          return true
        }
        return false
      },
    //  当前选中的三级分类的id
      cateId(){
        if (this.selectedKeys.length===3){
          return this.selectedKeys[this.selectedKeys.length -1]
        }else{
          return null;
        }
      },
    //  动态计算title
      titleText(){
        if (this.activeName==='many'){
          return '动态参数'
        }else{
          return '静态属性'
        }
      }

    },
    methods:{
      //  获取所有商品分类列表
      async getCateList(){
        this.cateList=catejson
        return
        const {data:res}=await this.$http.get('categories')
        if(res.meta!==200){
          return this.$message.error('获取商品分类信息失败')
        }
        this.cateList=res.data
      },
      async handleChange(){
        this.getParamsData()
      },
      //tab页签点击的处理函数
      handleTabClick(){
        this.getParamsData()
        console.log(this.activeName)
      },
      //  获取参数列表数据
      async getParamsData(){
        //级联选择框选中项，会触发这个方法,证明选中的不是三级（最明细）
        if(this.selectedKeys.length!==3){
          this.selectedKeys=[]
          this.manyTableData=[]
          this.onlyTableData=[]
          return
        }
        //  选中的是3级分类
        // console.log(this.selectedKeys)
        // console.log(paramsjson)
        let json
        if(this.activeName==='many'){
          json=manyjson;
          this.manyTableData=manyjson;
        }else{
          json=onlyjson;
          this.onlyTableData=onlyjson;
        }
        console.log(json)

        json.forEach(item=>{
          if(Array.isArray(item)) {
            console.log(Array.isArray(item))
          }else{
            item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
            //控制文本框的显示与隐藏，动态控制文本框的显示和输入的值
            item.inputVisible=false
            item.inputValue=''
          }
        })
        // console.log(json)
        return
        //  根据所选三级的id和选中的面板获取对应的参数
        const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
          params:{
            sel:this.activeName
          }
        })
        if(res.meta.status!==200){
          return this.$message.error('获取参数列表失败')
        }
        console.log(res.data)
        if(this.activeName==='many'){
          this.manyTableData=res.data;
        }else{
          this.onlyTableData=res.data;
        }
      },
      //关闭
      addDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },
      async addParams(){
        //验证表单
        this.$refs.addFormRef.validate(valid=>{
          if(!valid){
            return this.$message.error('表单验证失败')
          }
        })

        const {data: res}=await this.$http.post(`categories/${this.cateId}/attribute`,{
          params:{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activeName
          }
        })
        if (res.meta.status!==200){
          return this.$message.error('添加参数失败')
        }
        this.$message.info('添加参数成功')
        this.getParamsData()
        addDialogVisible = false
      },
      async showEditDialog(attr_id){
        const {data:res}=await this.$http.get(`categories/${this.cateId}/${attr_id}`,{
          params:{
            attr_sel:this.activeName
          }
        })
        if(res.meta.status!==200){
          return this.$message.error('获取表单信息失败')
        }
        this.editForm=res.data
        this.editDialogVisible=true
      },
      editDialogClosed(){
        this.$refs.editFormRef.resetFields()
      },
      editParams(){
        this.$refs.editForm.validate(async valid=>{
          if (!valid) return

          return

          const {data:res}=await this.$http.put(`categories/${this.cateId}/attributs/' +
            '${this.editForm.attr_id}`,{
            params:{
              attr_name:this.editForm.attr_name,
              attr_sel:this.activeName
            }
          })
          if(res.meta.status!==200){
            return this.$message.error('修改失败')
          }
          this.$message.info('修改成功')
          //刷新列表
          this.getParamsData()
        })
        this.editDialogVisible=false
      },
      //删除
      async removeParams(attr_id){
        const confirmResult=await
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmResult!=='confirm'){
          return this.$message.info("取消了删除操作");
        }
        //开始删除
        const {data:res}=await this.$http.delete(`categories/${this.cateId}/attribute/
        ${attr_id}`)
        if(res.meta.state!==200){
          return this.$message.info("删除分类参数失败")
        }
        this.$message.info('删除分类参数成功')
        this.getParamsData()
      },
      //文本框输入焦点或者失去焦点
      handleInputConfirm(row){
        console.log('ok')
      },
      //点击按钮，显示文本输入框
      showInput(row){
        row.inputVisible=true
        console.log(row)
        //让文本框自动获得焦点
        //$nextTick，就是当前页面被重新渲染后，才能指定控件获取到焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm(row){
        if(row.inputValue.trim().length===0){
          row.inputValue=''
          row.inputVisible=false
          return
        }
        //如果不等于0，需要做后续处理
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue=''
        row.inputVisible=false

        saveAttribute(row)
      },
      //保存信息
      async saveAttribute(row){
        //  需要发起请求，保存本次操作
        const {data:res}=await this.$http.put(`categories/${this.cateId}/attribute/${row.attri_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        })
        if (res.mate.status!==200){
          return this.$message.error('修改参数项失败')
        }
        this.$message.success('修改参数成功')
      },
      //删除对应的参数和选项
      handleClose(i,row){
        row.attr_vals.splice(i,1)//删除
        this.saveAttribute(row)
      }
    }
  }
</script>

<style lang="less" scoped>
  .cat_opt{
    margin:15px 0;
  }
  .el-tag{
    margin: 5px;
  }
  .input-new-tag{
    width:120px
  }
</style>
